<template>
  <q-page class="content-center items-center">
    <q-form class="flex flex-center column">
      <q-input v-model="username"
               :rules="[val => !!val || 'Поле логин обязательно']"
               stack-label
               no-error-icon
               dense
               class="q-mt-md content-center"
               style="width: 300px; border-radius: 4px"
               type="login"
               label="Логин"
               @keydown.enter="login"/>

      <q-input v-model="password"
               :rules="[val => !!val || 'Поле пароль обязательно']"
               stack-label
               no-error-icon
               dense
               class="q-mt-md"
               style="width: 300px; border-radius: 4px"
               type="password"
               label="Пароль"
               @keydown.enter="login"/>

      <q-btn class="q-mt-md"
             color="primary"
             style="width: 300px; border-radius: 4px"
             @click="login">
        {{ 'Войти' }}
      </q-btn>
    </q-form>
  </q-page>
</template>

<script setup>
import { authStore } from "stores/auth-store";
import { ref } from "vue";
import { useRouter } from 'vue-router'

const auth = authStore()
const username = ref('')
const password = ref('')

const router = useRouter()

const isLoading = ref(false)

const login = async () => {
  if (isLoading.value) {
    return
  }
  isLoading.value = true
  try {
    await auth.login({ username: username.value, password: password.value})
    await auth.getUserSelf()
    await router.push({ path: '/my-profile' })
  } catch (err) {
    console.error(err)
  } finally {
    isLoading.value = false
  }
}


defineOptions({
  name: 'LoginPage'
});
</script>

<style lang="scss" scoped>

</style>
